# -*- coding:utf-8 -*-
import signal

import time
import os
import sys
import subprocess
import platform

sys.path.append(os.path.abspath('.'))


class SystemUtils:
    cur_sys_type = -1
    SYS_TYPE_WIN = 0
    SYS_TYPE_LINUX = 1
    SYS_TYPE_OTHER = 2

    @staticmethod
    def judgeSystemType() -> int:
        if SystemUtils.cur_sys_type == -1:
            sys_platform = platform.system()
            if sys_platform == "Windows":
                SystemUtils.cur_sys_type = SystemUtils.SYS_TYPE_WIN
            elif sys_platform == "Linux":
                SystemUtils.cur_sys_type = SystemUtils.SYS_TYPE_LINUX
            else:
                SystemUtils.cur_sys_type = SystemUtils.SYS_TYPE_OTHER
        return SystemUtils.cur_sys_type

    # 统一执行 os.system() 命令
    @staticmethod
    def execute_os_sys_cmd(cmd: str):
        os.system(cmd)

    @staticmethod
    def execute_os_popen_cmd(cmd:str)-> str:
        return os.popen(cmd).read()

    # 延时(阻塞的)
    @staticmethod
    def delayTime(sleepSecond):  # 延迟x秒
        SystemUtils.delayTime(sleepSecond)

    @staticmethod
    def killProcess(proc):
        print("killProcess pid=" + str(proc.pid))
        try:
            if hasattr(os, 'setsid'):
                os.killpg(proc.pid, signal.SIGKILL)
            else:
                SystemUtils.execute_os_sys_cmd('taskkill.exe /pid:' + str(proc.pid))  # for windows
        except Exception as error:
            print("timeout_callback,error=" + str(error))

    #  该方法执行命令行命令，一次获取所有输出，并根据 filter 返回该行
    @staticmethod
    def execute_cmd_task_lines(cmd, filter_str) -> str:
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        for line in p.stdout.readlines():
            decode_content = line.decode('utf-8')
            result = decode_content.strip().rfind(filter_str)
            if result != -1:
                return decode_content
